{extend name="layout/main" /}

{block name="style"}
<style>
    .filter-bar {
        background: white;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .filter-form {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 15px;
        align-items: end;
    }
    
    .form-group {
        display: flex;
        flex-direction: column;
        gap: 5px;
    }
    
    .form-group label {
        font-size: 12px;
        color: #666;
        font-weight: 500;
    }
    
    .form-control {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
    }
    
    .form-control:focus {
        outline: none;
        border-color: #3498db;
        box-shadow: 0 0 5px rgba(52, 152, 219, 0.3);
    }
    
    .stats-bar {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
    }
    
    .stat-item {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        text-align: center;
        transition: transform 0.2s;
    }
    
    .stat-item:hover {
        transform: translateY(-2px);
    }
    
    .stat-number {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .stat-label {
        color: #666;
        font-size: 14px;
    }
    
    .table-container {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        overflow: hidden;
    }
    
    .table {
        width: 100%;
        border-collapse: collapse;
    }
    
    .table th,
    .table td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #f0f0f0;
        vertical-align: middle;
    }
    
    .table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #333;
        white-space: nowrap;
    }
    
    .table tbody tr:hover {
        background: #f8f9fa;
    }
    
    .status-badge {
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        white-space: nowrap;
    }
    
    .status-1 { background: #e3f2fd; color: #1976d2; } /* 填写中 */
    .status-2 { background: #fff3e0; color: #f57c00; } /* 已提交 */
    .status-3 { background: #f3e5f5; color: #7b1fa2; } /* 代签约 */
    .status-4 { background: #ffebee; color: #d32f2f; } /* 已驳回 */
    .status-5 { background: #e8f5e8; color: #388e3c; } /* 待打款 */
    .status-0 { background: #e8f5e8; color: #2e7d32; } /* 成功 */
    
    .type-badge {
        padding: 3px 6px;
        border-radius: 8px;
        font-size: 11px;
        font-weight: 500;
    }
    
    .type-2 { background: #e3f2fd; color: #1976d2; } /* 企业 */
    .type-4 { background: #fff3e0; color: #f57c00; } /* 个体工商户 */
    
    .merchant-info {
        display: flex;
        flex-direction: column;
        gap: 3px;
    }
    
    .merchant-name {
        font-weight: 500;
        color: #333;
    }
    
    .merchant-store {
        font-size: 12px;
        color: #666;
    }
    
    .contact-info {
        display: flex;
        flex-direction: column;
        gap: 3px;
    }
    
    .contact-name {
        font-weight: 500;
        color: #333;
    }
    
    .contact-mobile {
        font-size: 12px;
        color: #666;
    }
    
    .action-buttons {
        display: flex;
        gap: 5px;
        flex-wrap: wrap;
    }
    
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
        gap: 10px;
    }
    
    .pagination a,
    .pagination span {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        text-decoration: none;
        color: #333;
    }
    
    .pagination a:hover {
        background: #f8f9fa;
    }
    
    .pagination .current {
        background: #3498db;
        color: white;
        border-color: #3498db;
    }
    
    .mch-id-info {
        display: flex;
        flex-direction: column;
        gap: 3px;
    }
    
    .mch-id {
        font-family: monospace;
        font-size: 12px;
        color: #666;
    }
    
    @media (max-width: 768px) {
        .filter-form {
            grid-template-columns: 1fr;
        }
        
        .table-container {
            overflow-x: auto;
        }
        
        .action-buttons {
            flex-direction: column;
        }
        
        .stats-bar {
            grid-template-columns: repeat(2, 1fr);
        }
    }
</style>
{/block}

{block name="breadcrumb"}
<span class="breadcrumb-item">首页</span>
<span class="breadcrumb-item active">商户列表</span>
{/block}

{block name="content"}
<!-- 统计栏 -->
<div class="stats-bar">
    <div class="stat-item">
        <div class="stat-number" style="color: #3498db;">{$statistics.total}</div>
        <div class="stat-label">商户总数</div>
    </div>
    <div class="stat-item">
        <div class="stat-number" style="color: #f39c12;">{$statistics.pending}</div>
        <div class="stat-label">已提交</div>
    </div>
    <div class="stat-item">
        <div class="stat-number" style="color: #27ae60;">{$statistics.approved}</div>
        <div class="stat-label">成功</div>
    </div>
    <div class="stat-item">
        <div class="stat-number" style="color: #e74c3c;">{$statistics.rejected}</div>
        <div class="stat-label">已驳回</div>
    </div>
    <div class="stat-item">
        <div class="stat-number" style="color: #9b59b6;">{$statistics.individual}</div>
        <div class="stat-label">个体户</div>
    </div>
    <div class="stat-item">
        <div class="stat-number" style="color: #34495e;">{$statistics.enterprise}</div>
        <div class="stat-label">企业</div>
    </div>
</div>

<!-- 筛选栏 -->
<div class="filter-bar">
    <form class="filter-form" method="get">
        <div class="form-group">
            <label>状态筛选</label>
            <select name="status" class="form-control">
                <option value="">全部状态</option>
                <option value="1" {if $status == '1'}selected{/if}>填写中</option>
                <option value="2" {if $status == '2'}selected{/if}>已提交</option>
                <option value="3" {if $status == '3'}selected{/if}>代签约</option>
                <option value="4" {if $status == '4'}selected{/if}>已驳回</option>
                <option value="5" {if $status == '5'}selected{/if}>待打款</option>
                <option value="0" {if $status == '0'}selected{/if}>成功</option>
            </select>
        </div>
        <div class="form-group">
            <label>商户类型</label>
            <select name="type" class="form-control">
                <option value="">全部类型</option>
                <option value="2" {if $type == '2'}selected{/if}>企业</option>
                <option value="4" {if $type == '4'}selected{/if}>个体工商户</option>
            </select>
        </div>
        <div class="form-group">
            <label>关键词搜索</label>
            <input type="text" name="keyword" class="form-control" placeholder="商户名/店铺名/法人/手机号/身份证" value="{$keyword}">
        </div>
        <div class="form-group">
            <button type="submit" class="btn">搜索</button>
        </div>
        <div class="form-group">
            <a href="/admin/merchant" class="btn" style="background: #95a5a6;">重置</a>
        </div>
    </form>
</div>

<!-- 商户列表 -->
<div class="table-container">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>商户信息</th>
                <th>类型</th>
                <th>联系人信息</th>
                <th>微信商户号</th>
                <th>状态</th>
                <th>申请时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {volist name="merchants" id="merchant"}
            <tr>
                <td>{$merchant.id}</td>
                <td>
                    <div class="merchant-info">
                        <div class="merchant-name">{$merchant.merchant_name|default='--'}</div>
                        <div class="merchant-store">{$merchant.name}</div>
                        {if !empty($merchant.name)}
                        <div class="merchant-store">品牌：{$merchant.store_name|default='--'}</div>
                        {/if}
                    </div>
                </td>
                <td>
                    <span class="type-badge type-{$merchant.type}">
                        {if $merchant.type == 2}企业{elseif $merchant.type == 4}个体户{else}未知{/if}
                    </span>
                </td>
                <td>
                    <div class="contact-info">
                        <div class="contact-name">{$merchant.legal_person|default='--'}</div>
                        <div class="contact-mobile">{$merchant.mobile|default='--'}</div>
                        {if !empty($merchant.email)}
                        <div class="contact-mobile">{$merchant.email}</div>
                        {/if}
                    </div>
                </td>
                <td>
                    <div class="mch-id-info">
                        {if !empty($merchant.sub_mchid)}
                        <div class="mch-id">{$merchant.sub_mchid}</div>
                        {else}
                        <span style="color: #999;">--</span>
                        {/if}
                        {if !empty($merchant.applyment_id)}
                        <div class="mch-id">申请单：{$merchant.applyment_id}</div>
                        {/if}
                    </div>
                </td>
                <td>
                    <span class="status-badge status-{$merchant.status}">
                        {switch name="merchant.status"}
                            {case value="1"}填写中{/case}
                            {case value="2"}已提交{/case}
                            {case value="3"}代签约{/case}
                            {case value="4"}已驳回{/case}
                            {case value="5"}待打款{/case}
                            {case value="0"}成功{/case}
                            {default /}未知
                        {/switch}
                    </span>
                </td>
                <td>{$merchant.create_time|date='Y-m-d H:i'}</td>
                <td>
                    <div class="action-buttons">
                        <a href="/admin/merchant/detail/{$merchant.id}" class="btn btn-sm">详情</a>
                        {if $merchant.status == 0}
                        <button class="btn btn-sm" data-store="{$merchant.store_name|default=''}" onclick="openQrModal(this,'{$merchant.id}')">二维码</button>
                        {/if}
<!--                        {if $merchant.status == 2}-->
<!--                            <button class="btn btn-sm btn-success" onclick="approveMerchant({$merchant.id})">通过</button>-->
<!--                            <button class="btn btn-sm btn-warning" onclick="rejectMerchant({$merchant.id})">驳回</button>-->
<!--                        {/if}-->
<!--                        <button class="btn btn-sm btn-danger" onclick="deleteMerchant({$merchant.id})">删除</button>-->
                    </div>
                </td>
            </tr>
            {/volist}
        </tbody>
    </table>
    
    {if empty($merchants)}
    <div style="text-align: center; padding: 40px; color: #666;">
        暂无商户数据
    </div>
    {/if}
    
    <!-- 分页 -->
    {if isset($merchants) && $merchants->total() > 0}
    <div class="pagination">
        {$merchants->render()}
    </div>
    {/if}
</div>

<!-- 审核模态框 -->
<div id="approveModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; min-width: 400px;">
        <h3 style="margin-bottom: 20px;">审核通过</h3>
        <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 5px;">备注信息（可选）：</label>
            <textarea id="approveRemark" style="width: 100%; height: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" placeholder="请输入审核备注..."></textarea>
        </div>
        <div style="text-align: right;">
            <button class="btn" style="background: #95a5a6; margin-right: 10px;" onclick="closeModal('approveModal')">取消</button>
            <button class="btn btn-success" onclick="confirmApprove()">确认通过</button>
        </div>
    </div>
</div>

<div id="rejectModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 8px; min-width: 400px;">
        <h3 style="margin-bottom: 20px;">审核驳回</h3>
        <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 5px;">驳回原因（必填）：</label>
            <textarea id="rejectReason" style="width: 100%; height: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" placeholder="请输入驳回原因..."></textarea>
        </div>
        <div style="text-align: right;">
            <button class="btn" style="background: #95a5a6; margin-right: 10px;" onclick="closeModal('rejectModal')">取消</button>
            <button class="btn btn-danger" onclick="confirmReject()">确认驳回</button>
        </div>
    </div>
</div>

<!-- 二维码模态框 -->
<div id="qrModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; padding: 24px; border-radius: 12px; min-width: 380px; text-align: center; box-shadow: 0 8px 24px rgba(0,0,0,0.15);">
        <div style="font-size: 16px; font-weight: 600; color: #111; margin-bottom: 4px;">收款二维码</div>
        <div id="qrStoreName" style="margin-bottom: 12px; font-weight: 600; color: #333; font-size: 14px;"></div>
        <div style="margin-bottom: 16px; display: flex; justify-content: center;">
            <img id="qrImage" src="" alt="QR Code" style="width: 240px; height: 240px; border-radius: 8px; background: #fff; border: 1px solid #eee; box-shadow: 0 2px 8px rgba(0,0,0,0.06);" />
        </div>
        <div style="font-size: 12px; color: #888; margin-bottom: 14px;">扫码向商家付款</div>
        <div style="display: flex; justify-content: center; gap: 10px;">
            <button id="qrDownload" class="btn btn-success" onclick="downloadQr()">下载二维码</button>
            <button class="btn" style="background: #95a5a6;" onclick="closeModal('qrModal')">关闭</button>
        </div>
        <canvas id="qrCanvas" width="360" height="420" style="display:none;"></canvas>
    </div>
</div>
{/block}

{block name="script"}
    let currentMerchantId = 0;
    
    // 审核通过
    function approveMerchant(id) {
        currentMerchantId = id;
        document.getElementById('approveModal').style.display = 'block';
        document.getElementById('approveRemark').value = '';
    }
    
    // 审核驳回
    function rejectMerchant(id) {
        currentMerchantId = id;
        document.getElementById('rejectModal').style.display = 'block';
        document.getElementById('rejectReason').value = '';
    }
    
    // 删除商户
    function deleteMerchant(id) {
        if (confirm('确定要删除这个商户吗？此操作不可恢复！')) {
            fetch('/admin/merchant/delete/' + id, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('删除成功');
                    location.reload();
                } else {
                    alert('删除失败：' + data.msg);
                }
            })
            .catch(error => {
                alert('操作失败，请重试');
            });
        }
    }
    
    // 打开二维码模态框
    function openQrModal(btn, id) {
        const modal = document.getElementById('qrModal');
        const img = document.getElementById('qrImage');
        const dl = document.getElementById('qrDownload');
        const storeNameEl = document.getElementById('qrStoreName');
        const storeName = btn && btn.getAttribute('data-store') ? btn.getAttribute('data-store') : '';
        const targetUrl = 'https://jinjian.qianjuke888.com/api/cashier/' + id;
        const primary = 'https://quickchart.io/qr?text=' + encodeURIComponent(targetUrl) + '&size=220&margin=0';
        const fallback = 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&margin=0&data=' + encodeURIComponent(targetUrl);
        
        // 不存储链接地址到DOM属性中，避免被显示
        storeNameEl.textContent = storeName || '';
        img.onerror = function () {
            if (img.src !== fallback) {
                img.src = fallback;
            }
        };
        img.src = primary;
        dl.setAttribute('download', 'merchant-' + id + '-qr.png');
        modal.style.display = 'block';
    }

    // 在新页面打开并尝试直接下载
    function downloadQr() {
        const img = document.getElementById('qrImage');
        const canvas = document.getElementById('qrCanvas');
        const ctx = canvas.getContext('2d');
        const storeName = (document.getElementById('qrStoreName').textContent || '').trim();
        
        // 从当前显示的二维码图片URL中提取商户ID
        const src = img && img.src ? img.src : '';
        if (!src) return;
        
        // 从图片URL中提取商户ID，用于生成文件名
        const id = currentMerchantId || 'unknown';
        const filename = (storeName ? storeName + '-' : 'merchant-') + id + '-qr.png';

        // 画布尺寸：顶部店铺名 + 二维码 + 提示文案，尽量贴近微信样式
        const width = 360;
        const qrSize = 240;
        const padding = 20;
        const titleHeight = storeName ? 28 : 0;
        const tipHeight = 18;
        const height = padding + titleHeight + qrSize + 12 + tipHeight + padding;
        canvas.width = width;
        canvas.height = height;

        // 背景
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, width, height);

        // 店铺/品牌名称
        if (storeName) {
            ctx.fillStyle = '#111111';
            ctx.font = '600 16px -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,\"Noto Sans\",\"Apple Color Emoji\",\"Segoe UI Emoji\"';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'top';
            ctx.fillText(storeName, width / 2, padding);
        }

        // 绘制二维码
        const qrY = padding + titleHeight;
        const qrX = (width - qrSize) / 2;
        const qrImg = new Image();
        qrImg.crossOrigin = 'anonymous';
        qrImg.onload = function() {
            ctx.drawImage(qrImg, qrX, qrY, qrSize, qrSize);

            // 提示文案
            ctx.fillStyle = '#888888';
            ctx.font = '12px -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,\"Noto Sans\"';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'top';
            ctx.fillText('扫码向商家付款', width / 2, qrY + qrSize + 12);

            // 生成图片并下载（新窗口打开）
            const dataUrl = canvas.toDataURL('image/png');
            const win = window.open('', '_blank');
            if (!win) return;
            try {
                win.document.write('<a id="dl" href="' + dataUrl + '" download="' + filename + '">download</a>');
                win.document.close();
                setTimeout(function(){
                    try { win.document.getElementById('dl').click(); } catch(e) {}
                }, 200);
            } catch (e) {
                win.location.href = dataUrl;
            }
        };
        qrImg.onerror = function () {
            // 若跨域导致拒绝，退化为直接打开图片
            const win = window.open(src, '_blank');
            if (!win) return;
        };
        qrImg.src = src;
    }

    // 确认审核通过
    function confirmApprove() {
        const remark = document.getElementById('approveRemark').value;
        
        fetch('/admin/merchant/approve/' + currentMerchantId, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'remark=' + encodeURIComponent(remark)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                alert('审核通过成功');
                closeModal('approveModal');
                location.reload();
            } else {
                alert('操作失败：' + data.msg);
            }
        })
        .catch(error => {
            alert('操作失败，请重试');
        });
    }
    
    // 确认审核驳回
    function confirmReject() {
        const reason = document.getElementById('rejectReason').value.trim();
        
        if (!reason) {
            alert('请填写驳回原因');
            return;
        }
        
        fetch('/admin/merchant/reject/' + currentMerchantId, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'reason=' + encodeURIComponent(reason)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                alert('审核驳回成功');
                closeModal('rejectModal');
                location.reload();
            } else {
                alert('操作失败：' + data.msg);
            }
        })
        .catch(error => {
            alert('操作失败，请重试');
        });
    }
    
    // 关闭模态框
    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
        currentMerchantId = 0;
    }
    
    // 点击模态框外部关闭
    document.addEventListener('click', function(e) {
        if (e.target.id === 'approveModal' || e.target.id === 'rejectModal') {
            closeModal(e.target.id);
        }
        if (e.target.id === 'qrModal') {
            closeModal('qrModal');
        }
    });
{/block}
